package structure

import "gddgame.cc/galaxy/utils"

type ListStruct struct {
}

func (execute *Execute) GetListExtendIndex(conn SafeConn, data Data, et ExtendType, index int) interface{} {
	c, _ := conn.Do("LINDEX", execute.GetExtendKey(data, et), index)
	if c == nil {
		return nil
	}
	return utils.ToString(c)
}

func (execute *Execute) GetListExtend(conn SafeConn, data Data, et ExtendType) []interface{} {
	//lrange 0,-1
	c, _ := conn.Do("LRANGE", execute.GetExtendKey(data, et), 0, -1)
	if c == nil {
		return nil
	}
	return utils.ToInterfaceSlice(utils.ToStringSlice(c.([]interface{})))
}

func (execute *Execute) CreateListExtend(conn SafeConn, data Data, et ExtendType, extend []interface{}) {
	if extend == nil {
		return
	}
	//conn.Watch(key)
	args := append([]interface{}{execute.GetExtendKey(data, et)}, extend...)
	_ = conn.Send("RPUSH", args...)
}

func (execute *Execute) ResetListExtend(conn SafeConn, data Data, et ExtendType, extend []interface{}) {
	if extend == nil {
		return
	}
	//conn.Watch(key)
	key := execute.GetExtendKey(data, et)
	_ = conn.Send("DEL", key)
	args := append([]interface{}{key}, extend...)
	_ = conn.Send("RPUSH", args...)
}

func (execute *Execute) UpdateListExtend(conn SafeConn, data Data, et ExtendType, extend []UpdateExtend) {
	key := execute.GetExtendKey(data, et)
	//conn.Watch(key)
	for _, value := range extend {
		_ = conn.Send("LSET", key, value.Index, value.Value)
	}
}

func (execute *Execute) IncrListExtend(conn SafeConn, data Data, et ExtendType, index int, value int) {
	key := execute.GetExtendKey(data, et)
	//conn.Watch(key)
	_ = conn.Send("EVAL", "local v = redis.pcall(\"LINDEX\", KEYS[1], ARGV[1])\nredis.pcall(\"LSET\", KEYS[1], ARGV[1], v+ARGV[2])", 1, key, index, value)
}

func (execute *Execute) IncrFromListExtend(conn SafeConn, data Data, et ExtendType, index int, value int) {
	key := execute.GetExtendKey(data, et)
	_ = conn.Send("EVAL", "local v1 = redis.pcall(\"LINDEX\", KEYS[1], ARGV[1])\nlocal v2 = redis.pcall(\"LINDEX\", KEYS[1], ARGV[2])\nredis.pcall(\"LSET\", KEYS[1], ARGV[1], v1+v2)", 1, key, index, value)

}
